<style scoped lang="scss">
::v-deep .el-table .cell {
  line-height: 40px;
  height: 40px;
}
::v-deep .el-table td,
.el-table th {
  padding: 8px 0px;
}
.explain-block {
  div {
    font-weight: 700;
    font-size: 14px;
  }
  p {
    margin: 5px;
    font-size: 12px;
    text-indent: 2em;
  }
}
.dialog__body {
  background-color: #f3f3fa;
  border: 1px solid #bbbbbb;
  height: 65vh;
  overflow-y: auto;
  position: relative;
  display: flex;
  flex-direction: column;
}

.button-group {
  margin: 20px 0 0 10px;
  display: flex;
  justify-content: flex-end;

  &__info {
    margin-right: 10px;
  }
}

.tab-group {
  margin: 10px 0 0 0;
  height: 100%;

  ::v-deep .el-aside {
    padding: 10px 0 0 10px;
  }

  ::v-deep .el-input {
    padding-bottom: 10px;
  }

  ::v-deep .el-tree {
    height: var(--tree-height);
    overflow-y: auto;
  }

  ::v-deep .el-main {
    padding: 10px 10px 0 10px;
  }
}

::v-deep .el-table th.is-leaf {
  background-color: #ffffff !important;
}

.button-group__footer {
  display: flex;
  flex-direction: row-reverse;
  margin: 20px 10px 10px 0;
  //position: absolute;
  //bottom: 5px;
  //right: 0;
  &__cancel {
    margin: 0 0 0 10px;
  }
}
</style>
<template>
  <div class="dialog__body">
    <div class="button-group">
      <el-popover placement="right" width="200" trigger="click">
        <div class="explain-block">
          <div>功能：</div>
          <p>{{ explainData.funDescription }}</p>
          <div>输入端口：</div>
          <p>{{ explainData.inPort }}</p>
          <div>输出端口：</div>
          <p>{{ explainData.outPort }}</p>
          <div>参数：</div>
          <p>{{ explainData.functionName }}</p>
        </div>
        <mine-button
          slot="reference"
          type="primary"
          class="button-group__info"
          @click="getExplainInfo('duplicate')"
          ><i class="iconfont icon-help-circle-line"></i>说明</mine-button
        >
      </el-popover>
    </div>
    <div class="tab-group">
      <el-container>
        <el-aside width="200px">
          <!-- <el-input
            placeholder="请输入字段名"
            suffix-icon="el-icon-search"
            v-model="searchInput"
          >
          </el-input> -->
          <el-tree
            :data="dataList"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :style="cssVars"
          ></el-tree>
        </el-aside>
        <el-main>
          <!-- :header-cell-style="{ 'text-align': 'center' }" -->
          <el-table
            class="table border-table"
            :data="tableData"
            style="width: 100%"
            v-loading="loading"
            :height="tableHeight"
            ref="multipleTable"
          >
            <el-table-column prop="name" label="字段名" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="name2" label="注释名" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="type" label="类型" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="操作" show-overflow-tooltip>
              <template slot-scope="scope">
                <mine-button type="delete" @click="detectRow(scope.row)"
                  >移除</mine-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!--                    <mine-pagination-->
          <!--                        @numberChange="numberChange"-->
          <!--                        :total="total"-->
          <!--                        :page-size="pageSize"-->
          <!--                        :current-page="currentPage">-->
          <!--                    </mine-pagination>-->
        </el-main>
      </el-container>
    </div>
    <div class="button-group__footer">
      <mine-button
        type="primary"
        secondary
        class="button-group__footer__cancel"
        @click="close"
        >取消</mine-button
      >
      <mine-button type="primary" @click="confirm">确定</mine-button>
    </div>
  </div>
</template>

<script>
import qs from "qs";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";

export default {
  name: "Deduplication",
  props: {
    currentOperatorData: {
      type: Object,
    },
    fileDataList: {
      type: Array,
    },
    currentProcessId: {
      type: String,
    },
  },
  data() {
    return {
      loading: false,
      tableData: [],
      searchInput: "",
      dataList: JSON.parse(JSON.stringify(this.fileDataList)),
      defaultProps: {
        children: "children",
        label: "name",
      },
      explainData: {}, // 说明数据
    };
  },
  computed: {
    tableHeight: function () {
      return 0.5 * window.innerHeight + "px";
    },
    cssVars() {
      return {
        "--tree-height": 0.4 * window.innerHeight - 50 + "px",
      };
    },
  },
  methods: {
    async getExplainInfo(type) {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/helpInfo/getTree?helpCode=${type}`,
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: {},
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.explainData = result?.data;
            } else {
              _self.$message.warning("获取说明信息失败！");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/helpInfo/getTree?helpCode=${type}`,
          "get",
          "application/json;charset=UTF-8",
          {},
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.explainData = res?.data;
            } else {
              this.$message.warning("获取说明信息失败！");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getOperatorExplain", type);
        if (res.data.success) {
          this.explainData = res.data?.data;
        } else {
          this.$message.warning("获取说明信息失败！");
        }
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    handleNodeClick(data) {
      // 移除当前点击的数据
      this.dataList = this.dataList.filter((item) => {
        if (data.id === item.id) {
          return false;
        }
        return true;
      });
      data.datafieldId = data.id;
      data.duplicate = data.name;
      // 添加到右边表格
      this.tableData.push(data);
    },
    close() {
      this.$emit("changeFlag");
    },
    // 当前行的删除
    detectRow(row) {
      // 移除当前点击的数据
      this.tableData = this.tableData.filter((item) => {
        if (row.id === item.id) {
          return false;
        }
        return true;
      });
      // 添加到左边表格
      this.dataList.push(row);
    },
    // 确定按钮
    async confirm() {
      this.tableData = this.tableData.map((item) => {
        return Object.assign(item, {
          processingId: this.currentOperatorData.id,
        });
      });
      let params = {
        key: "processingId",
        value: this.currentOperatorData.id,
        t: this.tableData,
      };

      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/feDuplicateRule/saveOrUpdateBatchBfClear?key=${params.key}&value=${params.value}`,
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: params.t,
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.$message.success("保存成功");
              _self.close();
            } else {
              _self.$message.error("保存失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/feDuplicateRule/saveOrUpdateBatchBfClear?key=${params.key}&value=${params.value}`,
          "post",
          "application/json;charset=UTF-8",
          params.t,
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.$message.success("保存成功");
              this.close();
            } else {
              this.$message.error("保存失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("postDuplication", params);
        if (res.status === 200) {
          this.$message.success("保存成功");
          this.close();
        } else {
          this.$message.error("保存失败");
        }
      }
    },
    // 根据算子id获取右边表格数据
    async getDuplicateTableByOperatorId() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/feDuplicateRule/list",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(
                { processingId: _self.currentOperatorData.id },
                { indices: false }
              ),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              // 匹配字段名并赋值name
              result.data.forEach((item) => {
                _self.dataList.forEach((ele) => {
                  if (item.id === ele.id) {
                    item.name = ele.name;
                    item.type = ele.type;
                  }
                });
              });
              // 根据右边回显列表过滤掉左边的列表
              _self.dataList = _self.dataList.filter((item) => {
                for (let i = 0; i < result.data.length; i++) {
                  if (item.id === result.data[i].id) {
                    return false;
                  }
                }
                return true;
              });
              _self.tableData = result.data;
            } else {
              _self.$message.error("获取重复值处理列表数据失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/feDuplicateRule/list",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(
            { processingId: this.currentOperatorData.id },
            { indices: false }
          ),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              // 匹配字段名并赋值name
              res.data.forEach((item) => {
                this.dataList.forEach((ele) => {
                  if (item.id === ele.id) {
                    item.name = ele.name;
                    item.type = ele.type;
                  }
                });
              });
              // 根据右边回显列表过滤掉左边的列表
              this.dataList = this.dataList.filter((item) => {
                for (let i = 0; i < res.data.length; i++) {
                  if (item.id === res.data[i].id) {
                    return false;
                  }
                }
                return true;
              });
              if (res.status === 200) {
                this.tableData = res.data;
              } else {
                this.$message.error("获取重复值处理列表数据失败");
              }
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch(
          "getDuplicateTableByOperatorId",
          this.currentOperatorData.id
        );
        // 匹配字段名并赋值name
        res.data.data.forEach((item) => {
          this.dataList.forEach((ele) => {
            if (item.id === ele.id) {
              item.name = ele.name;
              item.type = ele.type;
            }
          });
        });
        // 根据右边回显列表过滤掉左边的列表
        this.dataList = this.dataList.filter((item) => {
          for (let i = 0; i < res.data.data.length; i++) {
            if (item.id === res.data.data[i].id) {
              return false;
            }
          }
          return true;
        });
        if (res.data.status === 200) {
          this.tableData = res.data.data;
        } else {
          this.$message.error("获取重复值处理列表数据失败");
        }
      }
    },
  },
  created() {
    // setTimeout(() => {
    this.getDuplicateTableByOperatorId();
    // }, 200);
  },
};
</script>
